//
//  CNHomeTableViewController.m
//  BeeQuick_19
//
//  Created by tanky on 2016/9/23.
//  Copyright © 2016年 CN Team. All rights reserved.
//

#import "CNHomeTableViewController.h"
#import "CNADRotatorView.h"
#import "CNWebViewController.h"
#import "CNFuncButtonsView.h"
#import "CNDisplayView.h"
#import "CNBestSellerModel.h"
#import "CNGoodsDisplayView.h"
#import "CNBestSellerTableViewCell.h"
#import "CNButton.h"
#import "CNADRotatorModel.h"
#import "ADView.h"
#import "CNADModel.h"
#import "CNADController.h"
#import "CNNavViewController.h"
#import <MJRefresh.h>
#import "CNRefreshHeaderView.h"
#import "Scan_VC.h"
#import "CNMapViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>

@interface CNHomeTableViewController ()<SDCycleScrollViewDelegate>

@property(nonatomic,strong)NSArray *bestSellerData;
@property(nonatomic,strong)UIView *alphaView;
@property(nonatomic,strong)UIButton *titleBtn;

@end

@implementation CNHomeTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self loadNavigationItems];
    [self setupUI];
    [self setupNav];
    [self loadHeaderView];
    [self loadBestSellerData];
    // 显示AD
    dispatch_async(dispatch_get_main_queue(), ^{
        [self showAD];
    });
    
    
}

#pragma mark 加载NavItem控件
- (void)loadNavigationItems{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"bqqrscan"] style:UIBarButtonItemStylePlain target:self action:@selector(jumpToScan)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_search"] style:UIBarButtonItemStylePlain target:self action:@selector(jumpToSearch)];
}

- (void)loadMapController{
    [self.navigationController pushViewController:[CNMapViewController new] animated:YES];
}

#pragma mark 跳转到搜索控制器
- (void)jumpToSearch{
    [self.navigationController pushViewController:[NSClassFromString(@"CNSearchViewController") new]animated:YES];
}

#pragma mark 跳转到扫一扫
- (void)jumpToScan{
    Scan_VC *VC = [[Scan_VC alloc]init];
    [self.navigationController pushViewController:VC animated:YES];
}

#pragma mark 设置当前控制器View的属性
- (void)setupUI{
    
    self.view.backgroundColor = [UIColor colorWithRed:221 green:221 blue:221];
    self.tableView.rowHeight = 294;

    CNRefreshHeaderView *header = [CNRefreshHeaderView headerWithRefreshingBlock:^{
        
        self.title = @"";
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] init];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            self.title = @"首页";
            [self loadNavigationItems];
            
            [self.tableView.mj_header endRefreshing];
            
            [self loadAlertView];
        });
    }];
    self.tableView.mj_header = header;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 50, 0);
}

#pragma mark 提示框
- (void)loadAlertView{
    UILabel * tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 30)];
    tipLabel.center = self.tableView.center;
    [tipLabel setText:@"没有数据更新"];
    tipLabel.backgroundColor = [UIColor blackColor];
    tipLabel.layer.cornerRadius = 5;
    tipLabel.layer.masksToBounds = YES;
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:tipLabel];
    [UIView animateWithDuration:2.0 animations:^{
        tipLabel.alpha = 0.0;
    } completion:^(BOOL finished) {
        [tipLabel removeFromSuperview];
    }];
}

#pragma mark 设置nav的属性
- (void)setupNav{
//    self.navigationController.navigationBar.translucent = NO;
//    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:255 green:210 blue:43];
    self.automaticallyAdjustsScrollViewInsets = NO;
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsCompact];
//    [self.navigationController.navigationBar setShadowImage:[UIImage new]];
    // 设置透明
    [self.navigationController.navigationBar setShadowImage:[[UIImage alloc] init]];
    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    
    // 设置nav所有的tintColor默认为白色
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    // 默认nav是白色的
    [self.navigationController.navigationBar setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] }];
    
    CGFloat mapIconWidth = [UIScreen mainScreen].bounds.size.width / 2;
    CGFloat mapIconHeight = 44 / 2 + 6;
    CGFloat mapIconRadius = mapIconHeight / 2;
    CGFloat maxMarginCenterX = 28;
    
//    UIView *mapIcon = [[UIView alloc] init];
//    mapIcon.size = CGSizeMake(mapIconWidth, mapIconHeight - 6);
//    mapIcon.center = CGPointMake(mapIconWidth, mapIconHeight - 6);
//    mapIcon.backgroundColor = [UIColor colorWithWhite:0 alpha:.5];
//    mapIcon.layer.cornerRadius = mapIconRadius - 3;
//    [self.navigationController.navigationBar insertSubview: mapIcon atIndex:0];
//    self.mapIcon = mapIcon;
//    
//    UIView *leftIcon = [[UIView alloc] init];
//    leftIcon.size = CGSizeMake(mapIconRadius * 2, mapIconRadius * 2);
//    leftIcon.centerX = maxMarginCenterX;
//    leftIcon.centerY = mapIcon.centerY - 1;
//    leftIcon.backgroundColor = [UIColor colorWithWhite:0 alpha:.5];
//    leftIcon.layer.cornerRadius = mapIconRadius;
//    [self.navigationController.navigationBar insertSubview: leftIcon atIndex:0];
//    self.leftIcon = leftIcon;
//    
//    UIView *rightIcon = [[UIView alloc] init];
//    rightIcon.size = CGSizeMake(mapIconRadius * 2, mapIconRadius * 2);
//    rightIcon.centerX = [UIScreen mainScreen].bounds.size.width - maxMarginCenterX;
//    rightIcon.centerY = mapIcon.centerY - 1;
//    rightIcon.backgroundColor = [UIColor colorWithWhite:0 alpha:.5];
//    rightIcon.layer.cornerRadius = mapIconRadius;
//    [self.navigationController.navigationBar insertSubview: rightIcon atIndex:0];
//    self.rightIcon = rightIcon;
//
//    CGRect frame = self.navigationController.navigationBar.frame;
//    UIView *alphaView = [[UIView alloc] initWithFrame:CGRectMake(- mapIconWidth / 2, -32, frame.size.width, frame.size.height+20)];
//    alphaView.backgroundColor = [UIColor colorWithRed:255 green:210 blue:43];
//    alphaView.userInteractionEnabled = NO;
//    alphaView.alpha = 0;
//    self.alphaView = alphaView;
//    [mapIcon insertSubview:alphaView atIndex:0];
    UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [titleBtn setAdjustsImageWhenDisabled:NO];
    [titleBtn setTitle:@"  你在哪里呀 ▼  " forState:UIControlStateNormal];
    [titleBtn setBackgroundColor:[UIColor colorWithWhite:0 alpha:.5]];
    [titleBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    titleBtn.layer.cornerRadius = 14;
    [titleBtn.layer masksToBounds];
    titleBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [titleBtn sizeToFit];
    [titleBtn addTarget:self action:@selector(loadMapController) forControlEvents:UIControlEventTouchUpInside];
    self.titleBtn = titleBtn;
    self.navigationItem.titleView = self.titleBtn;
    
    CGFloat cenX = - self.titleBtn.centerX * 2 - 33;
    CGFloat cenY = - self.titleBtn.centerY * 2;
    CGRect frame = self.navigationController.navigationBar.frame;
    self.alphaView = [[UIView alloc] init];
    self.alphaView.centerX = cenX;
    self.alphaView.centerY = cenY;
    self.alphaView.size = CGSizeMake(frame.size.width, frame.size.height + 20);
    self.alphaView.backgroundColor = [UIColor colorWithRed:255 green:210 blue:43];
    self.alphaView.userInteractionEnabled = NO;
    self.alphaView.alpha = 0;
    
    //self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"bqqrscan"] style:UIBarButtonItemStylePlain target:self action:@selector(jumpToScan)];
//    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    [leftBtn setAdjustsImageWhenDisabled:NO];
//    [leftBtn setImage:[UIImage imageNamed:@"bqqrscan"] forState:UIControlStateNormal];
//    [leftBtn setBackgroundColor:[UIColor colorWithWhite:0 alpha:.5]];
//    leftBtn.layer.cornerRadius = 23.5;
//    [leftBtn.layer masksToBounds];
//    leftBtn.size = CGSizeMake(23.5, 23.5);
//    [leftBtn addTarget:self action:@selector(jumpToScan) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.leftBarButtonItem.customView = leftBtn;
}

#pragma mark 设置headerView
- (void)loadHeaderView{
    UIView *headerView = [[UIView alloc] init];
    CGFloat screenWidth =  [UIScreen mainScreen].bounds.size.width;
    /** 轮播器*/
    CGFloat ADVHeight = [UIScreen mainScreen].bounds.size.width / 750 * 281;
    CNADRotatorView *ADV = [[CNADRotatorView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, ADVHeight)];
    [headerView addSubview:ADV];
    
    /** 功能按钮*/
    CGFloat funcBtnsHeight = 100;
    CNFuncButtonsView *funcBtnsView = [[CNFuncButtonsView alloc] initWithFrame:CGRectMake(0, ADVHeight, screenWidth, funcBtnsHeight)];
    [headerView addSubview:funcBtnsView];
    
    /** 广告展示*/
    CNDisplayView *DV = [[CNDisplayView alloc] initWithFrame:CGRectMake(0, ADVHeight + funcBtnsHeight, screenWidth, ADVHeight * 4)];
    [headerView addSubview:DV];
    CGFloat headerViewHeight = ADVHeight * 5 + funcBtnsHeight;
    headerView.frame = CGRectMake(0, 0, screenWidth, headerViewHeight);
    
    self.tableView.tableHeaderView = headerView;
}

#pragma mark 加载热卖数据
- (void)loadBestSellerData{
    CNHTTPSessionManager *manager = [CNHTTPSessionManager sharedManager];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    
    [param setValue:@"2" forKey:@"call"];
    
    [manager request:CNHttpMethodPost componentUrlString:@"firstSell.json.php" parameters:param completion:^(id response, NSError *error) {
        if (response) {
            NSArray *array = [NSArray yy_modelArrayWithClass:[CNBestSellerModel class] json:[response valueForKey:@"data"]];
            //数据库后的array
            NSArray *completeArray = [[SQLiteManager sharedSQLiteManager] getValueWith:array];
            self.bestSellerData = completeArray.copy;
            [self.tableView reloadData];
            NSLog(@"%@",response);
        }
    }];
}

#pragma mark Button点击后跳转WebView的方法
- (void)jumpToWebViewWithButton:(CNButton *)btn{
    NSString *urlString = btn.urlString;
    CNWebViewController *webVC = [CNWebViewController webViewControllerWithURL:urlString];
    [self.navigationController pushViewController:webVC animated:YES];
}

#pragma mark Button点击后跳转WebView的方法
- (void)jumpToWebViewWithUrlString:(NSString *)urlString{
    CNWebViewController *webVC = [CNWebViewController webViewControllerWithURL:urlString];
    [self.navigationController pushViewController:webVC animated:YES];
}

#pragma mark 返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return (self.bestSellerData.count + 1) / 2;
}

#pragma mark 返回cell样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *bestSellerCellID = @"bestSeller_id";
    
    CNBestSellerTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:bestSellerCellID];
    if (cell != nil) {
        [cell removeFromSuperview];
    }
    cell = [[CNBestSellerTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:bestSellerCellID];
    NSMutableArray *doubleBSModel = [NSMutableArray array];
    [doubleBSModel addObject:self.bestSellerData[indexPath.row * 2]];
    if ((indexPath.row * 2 + 1) > self.bestSellerData.count) {
        [doubleBSModel addObject:self.bestSellerData[indexPath.row * 2]];
    }else{
        [doubleBSModel addObject:self.bestSellerData[indexPath.row * 2 + 1]];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.doubleBSModelData = doubleBSModel.copy;
    return cell;
}

#pragma mark - tabBar处理
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
    self.navigationController.navigationBar.hidden=NO;
//    [self.navigationController.navigationBar setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
    [self.navigationController.navigationBar insertSubview: self.alphaView atIndex:0];
    self.bestSellerData = [[SQLiteManager sharedSQLiteManager] getValueWith:self.bestSellerData];
//    [self loadBestSellerData];
    [self.tableView reloadData];
    [self.titleBtn insertSubview:self.alphaView atIndex:0];
}

- (void)viewWillDisappear:(BOOL)animated{
    [self.alphaView removeFromSuperview];
//    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:[UIColor colorWithRed:255 green:210 blue:43 alpha:self.alphaView.alpha]] forBarMetrics:UIBarMetricsDefault];
    
}

#pragma mark 上下滑动的时候 导航栏的透明状态
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat alphaHeight = [UIScreen mainScreen].bounds.size.width / 750 * 281 - 64;
    if(scrollView.contentOffset.y < alphaHeight){
        [self.titleBtn setBackgroundColor:[UIColor colorWithWhite:0 alpha:0.5 - scrollView.contentOffset.y / alphaHeight / 2]];
        self.alphaView.alpha = 0 + scrollView.contentOffset.y / alphaHeight;
    }else if(scrollView.contentOffset.y > alphaHeight){
        [self.titleBtn setBackgroundColor:[UIColor colorWithWhite:0 alpha:0]];
        self.alphaView.alpha = 1;
    }
}

#pragma mark 轮播器点击事件
- (void)cycleScrollView:(CNADRotatorView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    CNADRotatorModel *model = cycleScrollView.rotatorData[index];
    [self jumpToWebViewWithUrlString:model.toURL];
}


#pragma mark - 显示广告界面
#pragma mark 判断是否显示AD界面
- (void)showAD {
    
    // temp路径
    NSString* tempPath = NSTemporaryDirectory();
    // file路径
    NSString* filePath = [tempPath stringByAppendingPathComponent:@"userAD.archive"];
    
    // 解档
    CNADModel *model = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
    
    if (model) {
        
        //1、创建广告
        ADView *adView = [[ADView alloc] initWithFrame:[UIScreen mainScreen].bounds imgUrl:model.img_big_name adUrl:nil clickImg:^(NSString *clikImgUrl) {
            
            // 广告界面
            CNADController *ad = [CNADController new];
            ad.url = @"https://www.baidu.com/";
            CNNavViewController *nav = [[CNNavViewController alloc] initWithRootViewController:ad];
            [self presentViewController:nav animated:YES completion:^{
                adView.alpha = 0;
            }];
        }];
            
        //设置倒计时（默认3秒）
        adView.showTime = 5;
            
        //2、显示广告
        [adView show];
    }
                          
}



#pragma mark 添加到购物车按钮点击事件
- (void)addButtonClick:(CNButton *)addBtn{
    CNGoodsDisplayView *clickView = addBtn.superview;
    [[SQLiteManager sharedSQLiteManager] charu:clickView.model With:+1];
    clickView.model.count ++;
    [self changeShoppingCartAnimatWithButton:addBtn];
    [self decideGoodsCountDisplayWithButton:addBtn];
}

#pragma mark 删除商品按钮点击事件
- (void)minuesButtonClick:(CNButton *)minuesBtn{
    CNGoodsDisplayView *clickView = minuesBtn.superview;
    [[SQLiteManager sharedSQLiteManager] charu:clickView.model With:-1];
    clickView.model.count --;
    [self decideGoodsCountDisplayWithButton:minuesBtn];
}

#pragma mark 添加到购物车动画
- (void)changeShoppingCartAnimatWithButton:(UIButton *)btn{
    CNGoodsDisplayView *clickView = btn.superview;
    CGPoint startBeta = [clickView convertPoint:btn.center toView:self.tableView.window];
    CGPoint start = CGPointMake(startBeta.x - 70, startBeta.y - 169.5);
    // 1.做什么动画
    CAAnimationGroup* group = [[CAAnimationGroup alloc] init];
    // MARK:进入购物车路径动画
    CAKeyframeAnimation* anim = [[CAKeyframeAnimation alloc] init];
    // 修改位置
    anim.keyPath = @"position";
    
    // 画曲线
    UIBezierPath* path = [UIBezierPath bezierPath];
    [path moveToPoint:start];
    
    //转化坐标系
    // 转坐标 购物车 -> self.view
    
    CGPoint end = CGPointMake([UIScreen mainScreen].bounds.size.width / 4 * 3 -([UIScreen mainScreen].bounds.size.width / 4 /2), [UIScreen mainScreen].bounds.size.height - 22);
    
    
    [path addQuadCurveToPoint:end  controlPoint:CGPointMake(start.x+100, start.y-200)];
    // 设置路径
    anim.path = path.CGPath;
    
    
    //设置代理（隐式代理，不遵守协议）走销毁方法
    
    // 创建小红点
    UIImageView* redPointView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, (self.view.bounds.size.width-30) / 2, 160)];
    NSString *urlString = [clickView.model.img stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *newURLString = [urlString stringByReplacingOccurrencesOfString:@"," withString:@""];
    [redPointView sd_setImageWithURL:newURLString];
    redPointView.center = start;
    [self.view.window addSubview:redPointView];
    // MARK:自旋转动画
    // 1.创建动画对象(做什么动画)
    CABasicAnimation* anim1 = [[CABasicAnimation alloc] init];
    
    // 2.修改动画的属性(怎么做动画)
    // 修改的属性
    anim1.keyPath = @"transform.rotation";
    
    // 累加
    anim1.byValue = @(M_PI * 2 * 3); // 一圈
    
    
    //缩放
    CABasicAnimation *anim2 = [CABasicAnimation animation];
    anim2.toValue = [NSValue valueWithCGSize:CGSizeMake(0.1, 0.1)];
    anim2.keyPath = @"transform.scale";
    anim2.removedOnCompletion = YES;
    anim2.fillMode = kCAFillModeForwards;
    
    
    
    group.delegate = self;
    
    // MARK:添加核心动画
    group.animations = @[ anim,anim1,anim2 ];
    // 设置时间
    group.duration = 1;
    //    // 设置重复次数
    //    group.repeatCount = MAXFLOAT;
    //设置的时候 写在添加核心动画之前
    [group setValue:redPointView forKey:@"redPointView"];
    //    [redPointView.layer addAnimation:anim forKey:nil];
    [redPointView.layer addAnimation:group forKey:nil];
}

#pragma mark 判断商品数量是否显示

- (void)decideGoodsCountDisplayWithButton:(UIButton *)btn{
    CNGoodsDisplayView *clickView = btn.superview;
    if (clickView.model.count == 0) {
        clickView.minuesBtn.alpha = 0;
        clickView.countLabel.alpha = 0;
    }else{
        clickView.minuesBtn.alpha = 1;
        clickView.countLabel.alpha = 1;
        clickView.countLabel.text = [NSString stringWithFormat:@"%zd",clickView.model.count];
    }
}

#pragma mark - 核心动画完成
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    //在动画结束的时候,通过不同的anim对象,取同样的key.就可以获取到每次做动画的iamgeView
    UIView *view = [anim valueForKey:@"redPointView"];
    NSLog(@"%@",view);
    [view removeFromSuperview];
}

@end
